package org.jxkj.app

import java.text.SimpleDateFormat
import java.util.{Date, UUID}
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import org.jxkj.data.IDaoProvider

/**
 * 巡检告警
 */
object MonitorAlert {

  def calData(ss: SparkSession, sc: SparkContext, hTable: IDaoProvider,time: Array[String], step : Int): Unit = {
    import ss.implicits._
    var startTime = time(0)
    val endTime = time(1)

    val  pointDf=ss.sql("select point_code,point_name,assetid from  hms_cm_point where point_type='on-off' and monitor_flag='5' " )
    pointDf.createOrReplaceTempView("t_point")
    import ss.implicits._
    val point_code: Array[String] = pointDf.map(x=>x.getString(0)).collect()

    for(i <- 0 until  point_code.length){println(point_code(i))}

    //GetData.getBySecond(ss,sc,hTable,point_code,time,step,1)
    GetData.getNoLoop(ss,sc,hTable,point_code,time,step)
    //ss.sql("select * from t_ods_hbase_edos").show(500)

    //生成udf函数 可以在withcolumn里使用
//    val generateUUID = udf(() => UUID.randomUUID().toString.replace("-",""))
    val generateUUID = () => UUID.randomUUID().toString.replace("-","")

    //将自定义函数注册到SparkSQL里
    ss.udf.register("uuID", generateUUID)


    val resultDf =ss.sql("select uuID() alert_id,point_code,point_name,assetid,'XJ' alert_source" +
      ",1 alert_type,5 alert_level,'' description,'1' state" +
      ",createtime begin_time,'1970-01-01 00:00:00' last_time,'1970-01-01 00:00:00' end_time" +
      ",'0' confirm_state,'1970-01-01 00:00:00' confirm_date" +
      ",'GZB' project_id,'10000' org_id,'' sub_org_id,'' create_person,now() create_time,'' modify_person,now() modify_time  " +
      " from t_point a " +
      " join t_ods_hbase_edos_tmp b on b.checkPoint=a.point_code and b.pvalue=1"
    )
    //resultDf.show()
    val tablename="hms_ta_monitor_alert"
    val delString=s"delete from $tablename where begin_time between '$startTime' and '$endTime'"
    MysqlDml.delete2(delString)

    //写mysql
    resultDf.write
      .format("jdbc")
      .mode("append")
      .option("url",MysqlDml.url2)
      .option("dbtable",tablename)
      .option("user",MysqlDml.user2)
      .option("password",MysqlDml.password2)
      .option("driver",MysqlDml.driver2)
      .save()


  }
}
